package cn.wolfcode.wolf2w.mgrsite.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserFavors;
import cn.wolfcode.wolf2w.redis.service.IStatisticsVORedisService;
import cn.wolfcode.wolf2w.redis.service.IUserFavorRedisService;
import cn.wolfcode.wolf2w.redis.vo.StatisticsVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserFavorsService;
import cn.wolfcode.wolf2w.util.RedisKeysStandard;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听初始化vo数据到redis中
 */
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStatisticsVORedisService statisticsVORedisService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IUserFavorsService userFavorsService;
    @Autowired
    private IUserFavorRedisService userFavorRedisService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("------------------------Listening--------------------------");
        //查询数据库中所有的数据（攻略相关）
        List<Strategy> strategies = strategyService.list();
        // 遍历添加到redis中
        for (Strategy strategy : strategies) {
            // 判断当前的id是否已存在缓存中
            if (statisticsVORedisService.isExistSid(strategy.getId())){
                continue;
            }
            StatisticsVO vo = new StatisticsVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            statisticsVORedisService.setStatisticsVOInRedis(vo);
        }

        // 查询用户收藏列表
        List<UserFavors> favors = userFavorsService.list();
        if (favors.size() > 0) {
            for (UserFavors favor : favors) {
                String key = RedisKeysStandard.USER_FAVOR_STRATEGIES.addKeyMessage(favor.getUid());
                if(userFavorRedisService.isExist(key)){
                    continue;
                }
                userFavorRedisService.setUserFavor(key, JSON.toJSONString(favor.getFavorSid()));
            }
        }

    }
}
